<template>
	<view class="camera">
		<view class="list">
			<view class="image-item" :key="index" v-for="(item,index) in images">
				
				<image class="image" @click="previewImage(index)" :src="`${BASE_URL}/jeecg-system/sys/common/static/${item}`">
				</image>
				<u-icon class="close" @click="deleteImage(index)" v-if="!disabled" name="close-circle-fill" size="30"></u-icon>
			</view>
		</view>
		<view class="photo" v-if="!disabled && count != images.length" @click="chooseImage">
			<image class="image" src="../../static/camera.png"></image>
		</view>

		<!-- <canvas canvas-id="fCanvas" style="position: absolute; right: 100rpx;z-index: -333;" :style="imgStyle"></canvas> -->
	</view>
</template>
<script>
	const getTokenStorage = () => {
		let token = ''
		try {
			token = uni.getStorageSync('ACCESS_TOKEN')
		} catch (e) {
			//TODO handle the exception
		}
		return token
	}
	const getUserId = () => {
		let user_id = ''
		try{
			user_id = uni.getStorageSync('userInfo').id
		}catch(e){
			//TODO handle the exception
		}
		return user_id
	}
	import {
		UPLOAD
	} from '../../api/urls.js';

	import {
		BASE_URL
	} from '../../utils/baseUrl.js';

	export default {
		name: "camera",
		model: {
			prop: 'photos',
			event: 'change'
		},
		props: {
			photos: {
				type: String,
				default: ''
			},
			disabled: {
				type: Boolean,
				default: false,
			},
			count: {
				type: [Number, String],
				default: 9,
			}
		},
		watch: {
			photos(newData) {
				this.images = this.photos ? this.photos.split(',') : [];
			}
		},
		data() {
			return {
				BASE_URL,
				images: [], //展示图片地址
				imgStyle: {}, //图片样式
				time: require('../../static/images/time.png'),
				position: require('../../static/images/position.png'),
				location: require('../../static/images/location.png'),
				address: {}
			};
		},
		methods: {
			//预览图片
			previewImage(index) {
				const newImages = this.images.map(item => `${this.BASE_URL}/jeecg-system/sys/common/static/${item}`)
				uni.previewImage({
					current: index,
					urls: newImages,
					indicator: 'number',
					loop: true,
				})
			},
			//删除图片
			deleteImage(index) {
				this.images.splice(index, 1);
				this.$emit('change', this.images.join(','))
			},
			//点击拍照上传图片
			async chooseImage() {
				const _this = this;
				uni.chooseImage({
					count: parseInt(_this.count),
					sourceType: ['album', 'camera'],
					sizeType: ['original', 'compressed'],
					success(res) {
						//设计图片
						const tempFiles = res.tempFilePaths;
						uni.showLoading({
							title: '图片生成中，请勿操作!'
						})
						_this.formateImage(tempFiles);
						// uni.getLocation({
						// 	type: 'gcj02',
						// 	geocode: true,
						// 	isHighAccuracy: true,
						// 	success: function(data) {
						// 		_this.address = data
						// 		_this.formateImage(tempFiles);
						// 	},
						// 	fail(error) {
						// 		uni.hideLoading();
						// 		uni.showToast({
						// 			title: '图片生成错误，未定位到信息',
						// 			icon: 'none'
						// 		})
						// 	}
						// })
						
					},
				})
			},
			async formateImage(tempFiles) {
				const _this = this;
				const length = tempFiles.length;
				let _temFiles = [];
				for (let i = 0; i < length; i++) {
					// const temFile = await this.syntheticImages(tempFiles[i]);
					// _temFiles.push(temFile);
					_temFiles.push(tempFiles[i]);
					
				}
				try {
					let _promises = [];
					for (let i = 0; i < _temFiles.length; i++) {
						_promises.push(this.uploadImage(_temFiles[i]));
					}
					Promise.all(_promises).then(res => {
						uni.showToast({
							title: '上传成功',
							icon: 'none'
						})
						_this.images.push(...res);
						_this.$emit('change', _this.images.join(','))
					})
				} catch (err) {
					uni.showToast({
						title: '上传图片失败',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			},
			syntheticImages(imagSrc) {
				return new Promise((resolve, reject) => {
					const scale = 2;
					const rectHeight = 200;
					const _this = this;
					// const res = 
					uni.getImageInfo({
						src: imagSrc,
						success(res) {
							const {
								width,
								height
							} = res;
							_this.imgStyle = {
								width: width / scale + 'px',
								height: height / scale + 'px'
							};
							uni.getLocation({
								type: 'gcj02',
								geocode: true,
								isHighAccuracy: true,
								success: function(data) {
									const {
										latitude,
										longitude,
										address
									} = data;
									
									const ctx = uni.createCanvasContext('fCanvas'); //创建画布
									ctx.drawImage(imagSrc, 0, 0, width / scale, height / scale)
									ctx.rect(0, height / scale - rectHeight, width / scale,
										rectHeight)
									ctx.setFillStyle('#808080')
									ctx.setGlobalAlpha(0.6)
									ctx.fill()
									ctx.setGlobalAlpha(1)
									ctx.setFontSize(20) //字体大小
									ctx.setFillStyle('#fff') //字体颜色
									if (address) {
										ctx.fillText(
											`${address.city}${address.district}${address.poiName}`,
											40, height / scale - rectHeight + 40)
										ctx.drawImage(_this.location, 10, height / scale -
											rectHeight + 20, 25,
											25)
									}
									ctx.fillText(`${longitude},${latitude}`, 40, height /
										scale - rectHeight +
										80)
									ctx.drawImage(_this.position, 10, height / scale -
										rectHeight + 63, 20,
										20)
									ctx.fillText(_this.formatTime(), 40, height / scale -
										rectHeight + 120)
									ctx.drawImage(_this.time, 10, height / scale - rectHeight +
										102, 20, 20)
									ctx.draw(false, () => {
										setTimeout(() => {
											uni.canvasToTempFilePath({
												x: 0,
												y: 0,
												width: width / scale,
												height: height / scale,
												destWidth: width /
													scale,
												destHeight: height /
													scale,
												canvasId: 'fCanvas',
												quality: 1,
												success(res) {
													resolve(res
														.tempFilePath
													);
												}
											})
										}, 500)
									});
								},
								fail() {
									uni.hideLoading();
									uni.showToast({
										title: '照片水印生成失败，未获取到定位信息，请检查网络',
										icon: 'none'
									})
								}
							});
						},
						fail() {
							uni.hideLoading();
							uni.showToast({
								title: '图片生成错误',
								icon: 'none'
							})
						}
					})
				})
			},
			//格式化时间
			formatTime() {
				return this.$u.timeFormat((new Date()).getTime(), 'yyyy-mm-dd hh:MM:ss');
			},
			//上传图片
			uploadImage(file) {
				const _this = this;
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: BASE_URL + UPLOAD,
						filePath: file,
						name: 'file',
						formData: {
							biz: 'temp',
						},
						header: {
							'Authorization': getTokenStorage(),
							'client-id': 'app_erp',
							'user-id': getUserId()
						},
						success(res) {
							const _data = JSON.parse(res.data);
							resolve(_data.message);

						},
						fail(error) {
							reject(error);
						}
					})
				})
			}
		},
		mounted() {
			this.images = this.photos ? this.photos.split(',') : [];
		}
	}
</script>
<style lang="scss" scoped>
	.camera {
		display: flex;
		flex-wrap: wrap;
		position: relative;
		overflow: hidden;

		.list {
			display: flex;
			flex-wrap: wrap;

			.image-item {
				width: 108rpx;
				height: 108rpx;
				background: #F2F2F2;
				margin-right: 10rpx;
				margin-bottom: 10rpx;
				border-radius: 8rpx;
				position: relative;

				.image {
					width: 108rpx;
					height: 108rpx;
					display: block;
				}

				.close {
					position: absolute;
					width: 30rpx;
					height: 30rpx;
					right: 0;
					top: 0;
				}
			}
		}

		.photo {
			width: 108rpx;
			height: 108rpx;
			background: #F2F2F2;
			border-radius: 8rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			.image {
				width: 48rpx;
				height: 48rpx;
			}
		}
	}
</style>
